package link.chengguo.orangemall.service.oms.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import link.chengguo.orangemall.delivery.service.IDeliveryService;
import link.chengguo.orangemall.enums.*;
import link.chengguo.orangemall.jms.entity.JmsGoodsTypeTrack;
import link.chengguo.orangemall.jms.entity.JmsOrderTrack;
import link.chengguo.orangemall.jms.entity.JmsPickingOrderGoods;
import link.chengguo.orangemall.service.jms.IJmsGoodsTypeTrackService;
import link.chengguo.orangemall.service.jms.IJmsOrderTrackService;
import link.chengguo.orangemall.service.jms.IJmsPickingOrderGoodsService;
import link.chengguo.orangemall.oms.entity.*;
import link.chengguo.orangemall.oms.mapper.OmsOrderMapper;
import link.chengguo.orangemall.oms.mapper.OmsOrderOperateHistoryMapper;
import link.chengguo.orangemall.oms.vo.OmsMoneyInfoParam;
import link.chengguo.orangemall.oms.vo.OmsOrderDeliveryParam;
import link.chengguo.orangemall.oms.vo.OmsReceiverInfoParam;
import link.chengguo.orangemall.pms.entity.PmsProduct;
import link.chengguo.orangemall.pms.entity.PmsProductCategory;
import link.chengguo.orangemall.pms.mapper.PmsProductMapper;
import link.chengguo.orangemall.service.pms.IPmsProductCategoryService;
import link.chengguo.orangemall.service.oms.*;
import link.chengguo.orangemall.shms.entity.ShmsShopBillLog;
import link.chengguo.orangemall.shms.entity.ShmsShopInfo;
import link.chengguo.orangemall.service.shms.IShmsShopBillLogService;
import link.chengguo.orangemall.service.shms.IShmsShopInfoService;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.mapper.UmsMemberMapper;
import link.chengguo.orangemall.util.DateUtils;
import link.chengguo.orangemall.utils.ValidatorUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author chengguo
 * @since 2019-04-17
 */
@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOmsOrderService {

    @Resource
    private OmsOrderMapper orderMapper;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private PmsProductMapper productMapper;
    @Resource
    private IOmsOrderOperateHistoryService orderOperateHistoryDao;
    @Resource
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;
    @Resource
    private IOmsVerifyLogService omsVerifyLogService;
    @Resource
    private IOmsOrderSettingService orderSettingService;
    @Resource
    private IShmsShopBillLogService shopBillLogService;
    @Resource
    private IShmsShopInfoService shopInfoService;
    @Resource
    private IJmsOrderTrackService jmsOrderTrackService;
    @Resource
    private IJmsGoodsTypeTrackService jmsGoodsTypeTrackService;
    @Resource
    private IJmsPickingOrderGoodsService jmsPickingOrderGoodsService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Resource
    private IPmsProductCategoryService productCategoryService;

    @Resource
    private IDeliveryService deliveryService;


    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderMapper.delivery(deliveryParamList);
        if (count > 0) {
            //添加操作记录
            List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                    .map(omsOrderDeliveryParam -> {
                        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                        history.setOrderId(omsOrderDeliveryParam.getOrderId());
                        history.setCreateTime(new Date());
                        history.setOperateMan("后台管理员");
                        history.setPreStatus(OrderStatus.TO_DELIVER.getValue());
                        history.setOrderStatus(OrderStatus.DELIVERED.getValue());
                        history.setNote("完成发货");
                        return history;
                    }).collect(Collectors.toList());
            orderOperateHistoryDao.saveBatch(operateHistoryList);
        }
        return count;
    }

    @Override
    public int singleDelivery(OmsOrderDeliveryParam deliveryParamList) {
        OmsOrder order = new OmsOrder();
        order.setId(deliveryParamList.getOrderId());
        order.setDeliverySn(deliveryParamList.getDeliverySn());
        order.setDeliveryCompany(deliveryParamList.getDeliveryCompany());
        order.setStatus(OrderStatus.DELIVERED.getValue());
        //批量发货
        int count = orderMapper.updateById(order);
        if (count > 0) {

            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(deliveryParamList.getOrderId());
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setPreStatus(OrderStatus.TO_DELIVER.getValue());
            history.setOrderStatus(OrderStatus.DELIVERED.getValue());
            history.setNote("完成发货");


            orderOperateHistoryDao.save(history);
        }
        return count;
    }

    @Override
    public Map orderDayStatic(String date) {
        Map list = orderMapper.orderDayStatic(date);
        return list;
    }

    @Override
    public Map orderMonthStatic(String date) {
        Map list = orderMapper.orderMonthStatic(date);
        return list;
    }

    @Override
    public Object dayStatic(String date, Integer type) {
        List<OmsOrder> orders = orderMapper.listByDate(date, type);
        List<UmsMember> members = memberMapper.listByDate(date, type);
        List<PmsProduct> products = productMapper.listByDate(date, type);
        int nowOrderCount = 0; // 今日订单
        BigDecimal nowOrderPay = new BigDecimal(0); //今日销售总额
        for (OmsOrder order : orders) {
            if (order.getStatus() < 9) {
                nowOrderCount++;
                nowOrderPay = nowOrderPay.add(order.getPayAmount());
            }
        }
        int mallCount = 0; // 当日
        int femallount = 0; // 当日
        for (UmsMember member : members) {
            if (member.getGender() == null || member.getGender() == 1) {
                mallCount++;
            } else {
                femallount++;
            }
        }
        int onCount = 0;
        int offCount = 0;

        int noStock = 0;

        for (PmsProduct goods : products) {
            if (goods.getPublishStatus() == 1) { // 上架状态：0->下架；1->上架
                onCount++;
            }
            if (goods.getPublishStatus() == 0) { // 上架状态：0->下架；1->上架
                offCount++;
            }
            if (ValidatorUtils.empty(goods.getStock()) || goods.getStock() < 1) { // 上架状态：0->下架；1->上架
                noStock++;
            }
        }
        Map<String, Object> map = new HashMap();
        map.put("nowOrderCount", nowOrderCount);
        map.put("nowOrderPay", nowOrderPay);
        map.put("mallCount", mallCount);
        map.put("femallount", femallount);
        map.put("onCount", onCount);
        map.put("offCount", offCount);
        map.put("noStock", noStock);

        map.put("memberCount", memberMapper.selectCount(new QueryWrapper<>()));
        map.put("goodsCount", productMapper.selectCount(new QueryWrapper<>()));
        map.put("orderCount", orderMapper.selectCount(new QueryWrapper<>()));
        return map;

    }

    @Transactional
    @Override
    public int orderVerify(Long orderId) {
        //查询订单是否存在
        OmsOrder omsOrder= orderMapper.selectById(orderId);
        //更新核销状态+订单状态
//        if (omsOrder.getSendType().intValue()== SendType.CodeBuy.getValue()){//扫码购
//            omsOrder.setStatus(OrderStatus.Finished.getValue());//核销即完成
//            omsOrder.setVerifyStatus(VerifyStatus.Verifyed.getValue());
//        }else if(omsOrder.getSendType().intValue()== SendType.BookingConsume.getValue()){
//            omsOrder.setStatus(OrderStatus.Finished.getValue());//核销即完成
//            omsOrder.setVerifyStatus(VerifyStatus.Verifyed.getValue());
//        }
        omsOrder.setStatus(OrderStatus.Finished.getValue());//核销即完成
        omsOrder.setVerifyStatus(VerifyStatus.Verifyed.getValue());
        omsOrder.setVerifyTime(new Date());
        orderMapper.updateById(omsOrder);
        //添加核销记录
        OmsVerifyLog verifyLog=new OmsVerifyLog();
        verifyLog.setOrderId(omsOrder.getId());
        verifyLog.setMoney(omsOrder.getPayAmount());
        verifyLog.setType(1);
        verifyLog.setCode(omsOrder.getOrderSn());
        verifyLog.setCityCode(omsOrder.getCityCode());
        verifyLog.setShopId(omsOrder.getShopId());
        verifyLog.setStatus(1);
        verifyLog.setVerifyTime(new Date());
        verifyLog.setContent("商家后台点击核销操作");
        omsVerifyLogService.save(verifyLog);
        //添加操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(omsOrder.getStatus());
        history.setNote("订单核销" );
        orderOperateHistoryMapper.insert(history);

        //更新账单状态
        ShmsShopBillLog billLog=new ShmsShopBillLog();
        billLog.setOrderId(omsOrder.getId());
        billLog.setBillStatus(BillSettlementStatus.ReadySettlement.getValue());
        billLog.setUpdateTime(new Date());
        ShmsShopBillLog parm=new ShmsShopBillLog();
        parm.setOrderId(omsOrder.getId());
        shopBillLogService.update(billLog,new QueryWrapper<>(parm));
        return 1;
    }

    @Override
    public int close(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(OrderStatus.Closed.getValue());
        int count = orderMapper.update(record, new QueryWrapper<OmsOrder>().eq("delete_status", 0).in("id", ids));
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:" + note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.saveBatch(historyList);
        return count;
    }

    /**
     * 定时关闭超时未接单的订单
     * @return
     */
    @Transactional
    @Override
    public boolean manageOvertimeReceiptOrder() {
        List<OmsOrder> list=getOvertimeOrderList(1);
        System.out.println("待处理超时未接订单数量："+list.size());
        if (list.size()==0){
            return false;
        }
        for (OmsOrder order:list){

        }
        //执行退款操作
        return false;
    }

    /**
     * 定时关闭未支付的超时订单
     * @return
     */
    @Transactional
    @Override
    public boolean manageOvertimeOrderClose() {
        List<OmsOrder> list=getOvertimeOrderList(0);
        System.out.println("待关闭超时订单数量："+list.size());
        if (list.size()==0){
            return false;
        }
        List<Long> ids=new ArrayList<>();
        for (OmsOrder order:list){
            ids.add(order.getId());
        }
        close(ids,"订单超时关闭");
        return false;
    }

    /**
     * 查询超时订单
     * @param  type 0-超时未支付，1-超时未接单，2-超时未抢单，3-超时未确认,4-超时未评价
     */
    @Override
    public List<OmsOrder> getOvertimeOrderList(int type) {
        OmsOrderSetting orderSetting= orderSettingService.getOrderSettings();
        QueryWrapper queryWrapper=new QueryWrapper();
        Date date;
        switch (type){
            case 0:// 0-超时未支付,所有订单
                date= DateUtils.addDateMinutes(new Date(),-orderSetting.getNormalOrderOvertime());
                queryWrapper.eq("status",OrderStatus.Default.getValue());//未支付
                queryWrapper.le("create_time",date);
                break;
            case 1://超时未接单，非物流订单
                date=DateUtils.addDateMinutes(new Date(),-orderSetting.getReceiptOvertime());
                queryWrapper.eq("status",OrderStatus.WaitEnsure.getValue());//待接单
                queryWrapper.le("create_time",date);
                break;
            case 2://超时未抢单，配送订单
                date=DateUtils.addDateMinutes(new Date(),-orderSetting.getGrabOvertime());
                queryWrapper.eq("shipping_status", ShippingStatus.WaitGrab.getValue());//待抢单
                queryWrapper.le("create_time",date);
                break;
            case 3://超时未确认，物流订单、扫码订单、上门服务订单、自提订单
                date=DateUtils.addDateDays(new Date(),-orderSetting.getConfirmOvertime());
                //此处待细化
                queryWrapper.eq("status",OrderStatus.Finished.getValue());//待抢单
                queryWrapper.le("create_time",date);
                break;
            case 4://超时未评价
                date=DateUtils.addDateDays(new Date(),-orderSetting.getCommentOvertime());
                //此处待细化
                queryWrapper.eq("status",OrderStatus.Finished.getValue());//待抢单
                queryWrapper.le("create_time",date);
                break;
        }
        List<OmsOrder> list=orderMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public int updateWaitGet(Long orderId, Integer sendType) {
        OmsOrder record = new OmsOrder();
        record.setStatus(OrderStatus.Ensured.getValue());
        record.setShippingStatus(ShippingStatus.WaitFinish.getValue());
        record.setId(orderId);
        int count = orderMapper.updateById(record);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(record.getStatus());
        history.setNote("商家更新待取货状态-上门自提");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int refuseOrder(Long orderId, Integer sendType) {
        OmsOrder record = new OmsOrder();
        record.setStatus(OrderStatus.Closed.getValue());
        record.setId(orderId);
        orderMapper.updateById(record);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(record.getStatus());
        history.setNote("拒绝接单");
        orderOperateHistoryMapper.insert(history);
        //退款操作-------------待完善
        OmsOrder order=this.baseMapper.selectById(orderId);
        if (order.getPayType()== PayType.Balance.getValue()){
            //余额支付
        }else if(order.getPayType()== PayType.WxApplet.getValue()){
            //微信小程序
        }else if(order.getPayType()== PayType.WxApp.getValue()){
            //微信App
        }else if(order.getPayType()== PayType.Ali.getValue()){
            //支付宝
        }
        //插入操作记录
        OmsOrderOperateHistory history2 = new OmsOrderOperateHistory();
        history2.setOrderId(orderId);
        history2.setCreateTime(new Date());
        history2.setOperateMan("后台管理员");
        history2.setOrderStatus(record.getStatus());
        history2.setNote("自动退款操作---待完善代码");
        orderOperateHistoryMapper.insert(history2);
        return 1;
    }

    @Override
    public int ensureOrder(Long orderId,Integer sendType) {
        //判定是否需要进入拣货状态
        OmsOrder record = orderMapper.selectById(orderId);
        ShmsShopInfo shopInfo=shopInfoService.getById(record.getShopId());
        boolean pickingOpen=shopInfo.getPickingOpen()==1?true:false;
        record.setStatus(OrderStatus.Ensured.getValue());
        if (sendType==SendType.PlatformDelivery.getValue()){
            //平台配送--抢单
            record.setShippingStatus(ShippingStatus.WaitGrab.getValue());
            if (pickingOpen){
                record.setPickingStatus(PickingStatus.WaitGrab.getValue());
                this.addPickingOrder(record);
            }
            //进入配送系统
            boolean re=deliveryService.addOrder(record);
            if (re==false){
                throw new RuntimeException("订单进入配送系统失败");
            }else{
                System.out.println("订单已导入配送系统");
            }
        }else if (sendType==SendType.ShopDelivery.getValue()){
            //商家配送--备货
            record.setShippingStatus(ShippingStatus.ArrivedShop.getValue());
            if (pickingOpen){
                record.setPickingStatus(PickingStatus.WaitGrab.getValue());
                this.addPickingOrder(record);
            }
        }else if (sendType==SendType.ShopPickup.getValue()){
            //到店自提--备货
            record.setShippingStatus(ShippingStatus.ArrivedShop.getValue());
            if (pickingOpen){
                record.setPickingStatus(PickingStatus.WaitGrab.getValue());
                this.addPickingOrder(record);
            }
        }else if (sendType==SendType.BookingConsume.getValue()){
            //预约到店，待核销、待消费
            record.setVerifyStatus(VerifyStatus.WaitVerify.getValue());
        }else if (sendType==SendType.HourseService.getValue()){
            //上门服务--待发货、待服务
            record.setExpressStatus(ExpressStatus.ToDeliver.getValue());
        }
        record.setId(orderId);
        int count = orderMapper.updateById(record);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(record.getStatus());
        history.setNote("商家确认接单");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    /**
     * 订单进入拣货系统
     * @param order
     * @return
     */
    @Transactional
    @Override
    public boolean addPickingOrder(OmsOrder order) {
        //商品类型跟踪
        JmsGoodsTypeTrack goodsTypeTrack=new JmsGoodsTypeTrack();
        goodsTypeTrack.setOrderId(order.getId());
        goodsTypeTrack.setShopId(order.getShopId());
        goodsTypeTrack.setCityCode(order.getCityCode());
        //订单跟踪
        JmsOrderTrack orderTrack=new JmsOrderTrack();
        orderTrack.setOrderId(order.getId());
        orderTrack.setShopId(order.getShopId());
        orderTrack.setCityCode(order.getCityCode());
        //商品详情加入
        JmsPickingOrderGoods goods=new JmsPickingOrderGoods();
        goods.setOrderId(order.getId());
        goods.setShopId(order.getShopId());
        goods.setCityCode(order.getCityCode());

        //查询订单详情
        List<OmsOrderItem> items= orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", order.getId()));
       //商品数量，类型数量
        int goodsNumber=0;
        List<Long> typeIdList=new ArrayList<>();
        StringBuilder goodsTypeIds=new StringBuilder();
        StringBuilder goodsTypeNames=new StringBuilder();
        Map<Long,Long> orderItemIds= new HashMap<>();//分类ID，详情ID
        for (OmsOrderItem item:items){
            goodsNumber+=item.getProductQuantity();
            //查询顶级分类ID
            PmsProductCategory category=productCategoryService.getParentProductCategoryById(item.getProductCategoryId());
            orderItemIds.put(category.getId(),item.getId());
            if (!typeIdList.contains(category.getId())){
                typeIdList.add(category.getId());
                goodsTypeTrack.setGoodsTypeId(category.getId());
                goodsTypeTrack.setGoodsTypeName(category.getName());
                //累加商品数量
                goodsTypeTrack.setGoodsNumber(item.getProductQuantity());
                goodsTypeTrack.setOrderItemIds(""+item.getId());
                jmsGoodsTypeTrackService.addGoodsTypeTrack(goodsTypeTrack);
                goodsTypeIds.append(","+category.getId());
                goodsTypeNames.append(","+category.getName());
            }else{
                //根据分类查询goodsType。
                JmsGoodsTypeTrack goodsTypeTrack1=jmsGoodsTypeTrackService.getOne(new QueryWrapper<JmsGoodsTypeTrack>().eq("order_id",order.getId()).eq("goods_type_id",category.getId()));
                goodsTypeTrack1.setGoodsNumber(goodsTypeTrack1.getGoodsNumber()+item.getProductQuantity());
                goodsTypeTrack1.setOrderItemIds(goodsTypeTrack1.getOrderItemIds()+","+item.getId());
                jmsGoodsTypeTrackService.updateById(goodsTypeTrack1);
            }
            //添加待抢商品信息
            goods.setBarcode(item.getProductSkuCode());
            goods.setGoodsName(item.getProductName());
            goods.setOrderDetailId(item.getId());
            goods.setGoodsId(item.getProductId());
            goods.setGoodsImg(item.getProductPic());
            goods.setGoodsNumber(item.getProductQuantity());
            goods.setGoodsPrice(item.getProductPrice().toString());
            goods.setGoodsTypeId(category.getId().intValue());
            goods.setGoodsTypeName(category.getName());
            goods.setGoodsSku(item.getProductAttr());
            jmsPickingOrderGoodsService.addPickingOrderGoods(goods);
        }
        goodsTypeIds.delete(0,1);
        goodsTypeNames.delete(0,1);
        orderTrack.setGoodsTypeIds(goodsTypeIds.toString());
        orderTrack.setGoodsTypeNames(goodsTypeNames.toString());
        orderTrack.setGoodsNumber(goodsNumber);
        orderTrack.setGoodsTypeNumber(typeIdList.size());
        jmsOrderTrackService.addOrderTrack(orderTrack);
        return true;
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = orderMapper.updateById(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = orderMapper.updateById(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(new Date());
        int count = orderMapper.updateById(order);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(status);
        history.setNote("修改备注信息：" + note);
        orderOperateHistoryMapper.insert(history);
        return count;
    }
}
